<template>
  <el-form :model="form" ref="formRef" :rules="rules" inline-message>
    <el-table :data="tableData">
      <el-table-column v-for="item of columns" align="center" :label="item.label"
        :prop="item.field" :width="item.width ?? ''">
        <template #default="scope">
          <el-form-item :prop="`${item.field}-${scope.$index}`">
            <span style="width: 100%;" v-if="item.type === 'readonly'">{{ tableData[scope.$index][item.field] }}</span>
            <el-date-picker v-else-if="item.type === 'date'" :type="item.type"
              @update:model-value="(v) => form[`${item.field}-${scope.$index}`] = v"
              v-model="tableData[scope.$index][item.field]" value-format="YYYY-MM-DD" format="YYYY-MM-DD" />
            <el-input @update:model-value="(v) => form[`${item.field}-${scope.$index}`] = v"
              :disabled="item.config && item.config.disabled !== undefined ? item.config.disabled : false"
              v-model="tableData[scope.$index][item.field]" v-else/>
          </el-form-item>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
  <el-row justify="end" style="margin-top: 15px;">
    <el-button @click="handleSave" type="primary">确认</el-button>
    <el-button @click="$emit('callBack')">取消</el-button>
  </el-row>
</template>

<script setup lang="ts">
import { FormRules } from "element-plus";
const props = defineProps<{
    modelValue: {
        pageConfig: {
            modelData: { data: any[], columns: any[]; };
        }
    }
}>();


const columns = computed(()=>(props.modelValue.pageConfig && props.modelValue.pageConfig.modelData.columns) ?? [])

const formRef = useTemplateRef("formRef")
const form = reactive<Record<any, any>>({})
const tableData = ref<any[]>([]);
const rules = ref<FormRules>({})
const emit = defineEmits(["callBack"])

onMounted(() => {
  console.log("props",props)
  console.log("editable modlel data :", props.modelValue.pageConfig.modelData.data);
  load()
})


function load(){
  tableData.value = props.modelValue.pageConfig.modelData.data
  const newData = []
  tableData.value.forEach(row=>{
    let obj:Record<any,any> = {}
    Object.assign(obj, row)
    for (const item of columns.value) {
        console.log("item",item)
        if (item.defaultValue && !row[item.field]) {
            if (typeof item.defaultValue === 'function') {
                row[item.field] = item.defaultValue(row)
            } else {
                row[item.field] = item.defaultValue
            }
        } 
    }
    newData.push(obj)
  })
  console.log("nwe data",newData)
  tableData.value = newData
  newData.forEach((x, index) => {
    for (const key of Object.keys(x)) {
      form[`${key}-${index}`] = x[key]
    }
  })
  generateRules()
}

const generateRules = () => {
  props.modelValue.pageConfig.modelData.columns.forEach(x => {
    tableData.value.forEach((_, index) => {
      rules.value[`${x.field}-${index}`] = x.rule
    })
  })
  console.log("rules", rules.value)
}

watch(() => props.modelValue.pageConfig.modelData.data, (v) => {
    load()
},{immediate:true})

function handleSave(){
    formRef.value?.validate((validate)=>{
        if(validate) { 
            console.log("form",form)
            emit("callBack",tableData.value)
        }
    })
}

defineExpose({
  tableData,
  validate: computed(() => formRef.value?.validate)
})
</script>

<style scoped></style>
